package entity

import "src/zeus/iserver"

type EDPSorterType int8

const (
	EDPSorterTypeSync EDPSorterType = 1
	EDPSorterTypeSave EDPSorterType = 2
)

func NewDirtyPropSorter(sorterType EDPSorterType) IDirtyPropertySorter {
	switch sorterType {
	case EDPSorterTypeSync:
		return &DirtyPropListForSync{dirtyProps: make([]*PropInfo, 0, 1)}
	case EDPSorterTypeSave:
		return &DirtyPropListForSave{dirtyProps: make([]*PropInfo, 0, 1)}
	default:
		return nil
	}
}

type DirtyPropListForSync struct {
	dirtyProps []*PropInfo
}

func (e *DirtyPropListForSync) GetSorterType() EDPSorterType {
	return EDPSorterTypeSync
}

func (e *DirtyPropListForSync) TryAddToDirtyList(p *PropInfo) {
	if p.Def.Sync {
		if p.syncFlag == false {
			p.syncFlag = true
			e.dirtyProps = append(e.dirtyProps, p)
		}
	}
}

func (e *DirtyPropListForSync) HandlerForEach(consumeFunc func(p *PropInfo)) bool {
	return e.HandlerAllList(func(dirtyProps []*PropInfo) bool {
		for _, p := range dirtyProps {
			p.syncFlag = false
			consumeFunc(p)
		}
		return true
	})
}

func (e *DirtyPropListForSync) HandlerAllList(consumeListFunc func(list []*PropInfo) bool) bool {
	if len(e.dirtyProps) == 0 {
		return false
	}
	dirtyProps := e.dirtyProps
	e.dirtyProps = make([]*PropInfo, 0, 1)

	for _, p := range dirtyProps {
		p.syncFlag = false
	}
	return consumeListFunc(dirtyProps)
}

func (e *DirtyPropListForSync) ListCount() int {
	return len(e.dirtyProps)
}

type DirtyPropListForSave struct {
	dirtyProps []*PropInfo
}

func (e *DirtyPropListForSave) GetSorterType() EDPSorterType {
	return EDPSorterTypeSave
}

func (e *DirtyPropListForSave) TryAddToDirtyList(p *PropInfo) {
	//如果是场景服务器，属性Persistence只要是3就表示所有场景服都可以落地数据
	if p.Def.SaveSrvType == iserver.GetSrvInst().GetSaveType() {
		if p.dbFlag == false {
			p.dbFlag = true
			e.dirtyProps = append(e.dirtyProps, p)
		}
	}
}

func (e *DirtyPropListForSave) HandlerForEach(consumeFunc func(p *PropInfo)) bool {
	return e.HandlerAllList(func(dirtyProps []*PropInfo) bool {
		for _, p := range dirtyProps {
			p.dbFlag = false
			consumeFunc(p)
		}
		return true
	})
}

func (e *DirtyPropListForSave) HandlerAllList(consumeListFunc func(list []*PropInfo) bool) bool {
	if len(e.dirtyProps) == 0 {
		return false
	}
	dirtyProps := e.dirtyProps
	e.dirtyProps = make([]*PropInfo, 0, 1)

	for _, p := range dirtyProps {
		p.dbFlag = false
	}
	return consumeListFunc(dirtyProps)
}

func (e *DirtyPropListForSave) ListCount() int {
	return len(e.dirtyProps)
}
